import ReconnectingWebSocket from "reconnecting-websocket";
import { QWebChannel } from "qwebchannel";

var wsUri = "ws://localhost:12348";

export const link = function (fn?: (channel: any) => void, fn2?: (error: any) => void) {
  let isthrow = false;
  let runFn2 = function(error: any) {
    if(!isthrow) {
      isthrow = true;
      fn2 && fn2(error);
    }
  }
  return new Promise<any>((resolve, reject) => {
    var qchannel: QWebChannel;

    var socket = new ReconnectingWebSocket(wsUri, [], {
      connectionTimeout: 1000,
      maxRetries: 10,
      maxEnqueuedMessages: 1,
    });
    const transport = {
      send(data: string | ArrayBufferLike | Blob | ArrayBufferView) {
        socket.send(data);
      },
      onmessage(ev: MessageEvent) {},
    };
    socket.onmessage = function (evt) {
      transport.onmessage(evt);
    };
    socket.onclose = function () {
      // reCreateWebSocket(wsUri);
      runFn2(new Error("web channel closed"));
      console.error("web channel closed");
    };
    socket.onerror = function (error) {
      // reCreateWebSocket(wsUri);
      runFn2(error);
      console.error("web channel error: " + error);
      // reject(error)
    };
    socket.onopen = function () {
      if (!qchannel) {
        qchannel = new QWebChannel(transport, function (channel: any) {
          console.log(channel.objects);
          if (fn) fn(channel.objects);
          resolve(channel.objects)
        });
      }
    };
  });
};
